<template>
  <template v-if="isAlready">
    <template v-if="isReadonly">
      <template v-if="column.widgetType==='file'">
        <template v-if="column.listType==='text'">
          <div  style="width:100%;position: relative;top:5px;text-align: left;">
          <div class="fileTemp" v-for="file in tempFileList" :key="file.uid">
            <div class="fileTempleft">
					  <p @click="download(file)">{{ file.name }}</p>
          </div>
          <div class="fileTempright">
					  <el-icon @click="download(file)" style="cursor: pointer;margin-top: 6px;"><component is="el-icon-download"></component></el-icon>
				  </div>
          </div>
        </div>
      </template>
      <template v-else>
        <div class="avatar-uploader">
          <ul class="el-upload-list el-upload-list--picture-card">
            <li class="el-upload-list__item is-success" v-for="file in tempFileList">
              <img class="el-upload-list__item-thumbnail" :alt="file.name" :src="file.url">
              <span class="el-upload-list__item-actions">
				<el-icon @click="handlePictureCardPreview(file)" style="cursor: pointer"><component is="el-icon-zoom-in"></component></el-icon>
                <el-icon @click="download(file)" style="cursor: pointer;margin-left: 10px;"><component is="el-icon-download"></component></el-icon>
              </span>
            </li>
          </ul>
        </div>
      </template>
      </template>
      <template v-else>
        <template v-if="column.dataSourceCode">
          <template v-if="model[column.code]">
            <ex-label :value="model[column.code]" :code="column.dataSourceCode"/>
          </template>
          <template v-else>
            <ex-label :value="this.$t('common.empty')" code="EMPTY"/>
          </template>
        </template>
        <template v-else>
          <template v-if="model[column.code]">
			  <template  v-if="column.widgetType==='date' || column.widgetType==='datetime'" >
				  <ex-label format :value="model[column.code]" :code="column.widgetType.toUpperCase()"/>
			  </template>
			  <template v-else-if="model[column.code].length>12">
				<el-tooltip effect="dark" :content="model[column.code]" placement="top-start"
						:show-after="500"
						style="font-size:14px;">
				  		<div style="white-space: nowrap;overflow: clip;">{{ model[column.code] }}</div>
				</el-tooltip>
			  </template>
			  <template v-else>
				  <div style=" padding-top: 3px;
	  padding-right: 3px;" >{{ model[column.code] }}</div>
			  </template>
		  </template>
          <template v-else>
            <ex-label :value="this.$t('common.empty')" code="EMPTY"/>
          </template>
        </template>
      </template>
    </template>
  <template v-else>
      <el-input v-if="column.widgetType==='text'"
                v-model="model[column.code]"
                :size="column.widgetSize?column.widgetSize:size"
                :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_input')+(column.label||column.name)"
                :minlength="column.minLength!==undefined?column.minLength:null"
                :maxlength="column.maxLength!==undefined?column.maxLength:null"
                :show-word-limit="true"
                :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;'"
                clearable>
      </el-input>

      <el-input v-if="column.widgetType==='textarea'"
                v-model="model[column.code]"
                :size="column.widgetSize?column.widgetSize:size"
                :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_input')+(column.label||column.name)"
                :minlength="column.minLength!==undefined?column.minLength:null"
                :maxlength="column.maxLength!==undefined?column.maxLength:null"
                type="textarea"
                :show-word-limit="true"
                :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;'"
                :rows="column.height!==undefined?column.height:1"
                clearable>
      </el-input>

      <el-input-number v-if="column.widgetType==='number'"
                       v-model="model[column.code]"
                       :size="column.widgetSize?column.widgetSize:size"
                       :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_input')+(column.label||column.name)"
                       :min="column.minValue!==undefined?column.minValue:-999999999"
                       :max="column.maxValue!==undefined?column.maxValue:999999999"
                       :precision="0"
                       :step="1"
                       :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;'"
                       clearable>
      </el-input-number>

      <el-input-number v-if="column.widgetType==='decimal'"
                       v-model="model[column.code]"
                       :size="column.widgetSize?column.widgetSize:size"
                       :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_input')+(column.label||column.name)"
                       :min="column.minValue!==undefined?column.minValue:-999999999.99"
                       :max="column.minValue!==undefined?column.maxValue:999999999.99"
                       :step="0.01"
                       :precision="2"
                       :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;'"
                       clearable>
      </el-input-number>
	  <ex-radio-group v-if="column.widgetType==='radio'&&column.dataSourceCode"
					  v-model="model[column.code]"
					  :dict-code="column.dataSourceCode"
					  :is-pri-key="column.dataSourceType==='2'"
					  :size="column.widgetSize?column.widgetSize:size">
	  </ex-radio-group>

		<ex-check-box v-if="column.widgetType==='checkbox'&&column.dataSourceCode"
					  v-model="model[column.code]"
					  :dict-code="column.dataSourceCode"
					  :pri-key="column.dataSourceType==='2'"
					  :size="column.widgetSize?column.widgetSize:size">
		</ex-check-box>

      <el-switch v-if="column.widgetType==='switch'"
                 v-model="model[column.code]"
                 :size="column.widgetSize?column.widgetSize:size"
                 style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                 :active-value="'1'"
                 :inactive-value="'0'">
      </el-switch>

      <el-date-picker v-if="column.widgetType==='date' || column.widgetType==='datetime'"
                      v-model="model[column.code]"
                      :size="column.widgetSize?column.widgetSize:size"
                      :type="column.widgetType"
                      :format="column.widgetType==='date'?'YYYY-MM-DD':'YYYY-MM-DD HH:mm:ss'"
                      :value-format="column.widgetType==='date'?'YYYYMMDD':'YYYYMMDDHHmmss'"
                      :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_choose')+(column.label||column.name)"
                      :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;'"
                      clearable>
      </el-date-picker>

	  <ex-select v-if="column.widgetType==='select'&&column.dataSourceCode"
				 v-model="model[column.code]"
				 :dict-code="column.dataSourceCode"
				 :pri-key="column.dataSourceType==='2'"
				 :size="column.widgetSize?column.widgetSize:size"
				 :ops="column.ops"
				 :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_choose')+(column.label||column.name)"
				 :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;'"></ex-select>

      <el-cascader v-if="column.widgetType==='cascade'"
                   v-model="model[column.code]"
                   :size="column.widgetSize?column.widgetSize:size"
                   :options="cascadeOptions"
                   :props="cascadeProps"
                   :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;'"
                   :show-all-levels="false"
                   :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_choose')+(column.label||column.name)"
                   :popper-append-to-body="false"
                   filterable
                   clearable>
                   <template #default="{ node, data }">
                    <el-tooltip
                      :disabled="data.label.length < 8"
                      class="item"
                      effect="dark"
                      :content="data.label"
                      placement="top"
                      :show-after="500"
                      style="font-size:14px;"
                    >
                      <span>{{ data.label }}</span>
                    </el-tooltip>
                  </template>
      </el-cascader>


<!--	  <el-tree-select v-if="column.widgetType==='tree-select'"-->
<!--					  v-model="model[column.code]"-->
<!--					  :size="column.widgetSize?column.widgetSize:size"-->
<!--					  :multiple="column.multiple"-->
<!--					  :show-checkbox="column.multiple"-->
<!--					  :data="cascadeOptions"-->
<!--					  :props="cascadeProps"-->
<!--					  :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;max-height:200px;'"-->
<!--					  :show-all-levels="false"-->
<!--					  :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_choose')+(column.label||column.name)"-->
<!--					  filterable-->
<!--					  clearable>-->
<!--	  </el-tree-select>-->

<!--:multiple="column.multiple!==false"
					  :show-checkbox="column.multiple!==false"-->
	  <el-tree-select v-if="column.widgetType==='tree-select'"
					  ref="treeSelect"
					  v-model="model[column.code]"
					  :data="cascadeOptions"
					  :multiple="column.multiple!==false"
					  :show-checkbox="column.multiple!==false"
					  :check-strictly="true"
					  check-on-click-node
					  node-key="id"
					  :render-after-expand="true"
					  :style="column.width!==undefined?'width:'+column.width+'px;':'width:100%;'"
					  :placeholder="this.column.placeHolder?this.column.placeHolder:$t('common.please_choose')+(column.label||column.name)"
					  filterable
					  clearable @check="handleCheck">
	  </el-tree-select>

	  <ex-selector v-if="column.widgetType==='selector'" :code="column.dataSourceCode" :model="model" :prop="column.code" :column="column" :isicon="selectoricon" :params="{}"></ex-selector>

	  <template v-if="column.widgetType==='file'">
		  <template v-if="column.listType==='text'">
			  <el-upload v-model:file-list="tempFileList"
						 :class="column.height!==tempFileList.length?'avatar-uploader-button':'avatar-uploader-hidden'"
						 :limit="column.height!==undefined?column.height:1"
						 :show-file-list="false"
						 :on-exceed="handleExceed"
						 :before-upload="beforeUpload"
						 :on-success="handleSuccess"
						 :on-remove="handleRemove"
						 :on-preview="handlePictureCardPreview"
						 :http-request="submitUpload"
						 :auto-upload="true"
			  >
				  <el-button type="primary" icon="el-icon-upload">上传附件</el-button>
			  </el-upload>
			  <div  style="width:100%;position: relative;top:5px;text-align: left;">
				  <div class="fileTemp" v-for="file in tempFileList" :key="file.uid">
					<div class="fileTempleft">
						<p @click="download(file)">{{ file.name }}</p>
				  	</div>
				  	<div class="fileTempright">
					  <el-icon @click="removefile(file)" style="cursor: pointer;margin-top: 6px;margin-right: 6px;"><component is="el-icon-close"></component></el-icon>
					  <el-icon @click="download(file)" style="cursor: pointer;margin-top: 6px;"><component is="el-icon-download"></component></el-icon>
					</div>
				  </div>
			  </div>
		  </template>
		  <template v-else>
			  <el-upload v-model:file-list="tempFileList"
						 list-type="picture-card"
						 :class="column.height!==tempFileList.length?'avatar-uploader':'avatar-uploader-hidden'"
						 :limit="column.height!==undefined?column.height:1"
						 :show-file-list="true"
						 :on-exceed="handleExceed"
						 :before-upload="beforeUpload"
						 :on-success="handleSuccess"
						 :on-remove="handleRemove"
						 :on-preview="handlePictureCardPreview"
						 :http-request="submitUpload"
						 :auto-upload="true"
			  >
				  <template v-if="column.fileType==='image'">
					  <span style="color:var(--el-text-color-placeholder)">上传图片</span>
				  </template>
				  <template v-else>
					  <el-icon>
						  <component is="el-icon-plus"></component>
					  </el-icon>
				  </template>
			  </el-upload>
		  </template>
	  </template>
    </template>
	  <template v-if="column.widgetType==='file'">
        <el-dialog v-model="dialogVisible">
          <el-image v-if="dialogImageUrl" :src="dialogImageUrl" :preview-src-list="[dialogImageUrl]" :zIndex="99999"/>
        </el-dialog>
	  </template>
  </template>
</template>
<script>

import ExLabel from "@/components/exLabel/index.vue";
import ExSelector from "@/components/exSelector/index.vue";
import ExRadioGroup from "@/components/exRadioGroup/index.vue";
import ExSelect from "@/components/exSelect/index.vue";
import ExCheckBox from "@/components/exCheckBox/index.vue";
import tool from "@/utils/tool";
import jsQR from 'jsqr';
import { number } from "echarts";

export default {
  name: "exWidget",
  emits: ['changeHeight'],
  components: {ExCheckBox, ExSelect, ExRadioGroup, ExSelector, ExLabel},
  props: {
    column: {type: Object, default: null},
    size: {type: String, default: ''},
    model: {type: Object, default: null},
	topModel: {type: Object, default: {}},
    drag: {type: Boolean, default: false},
    colitemheight:{type:Number,default:0}
  },
  data() {
    return {
	  tempFileList: [],
      isAlready: false,
      imageUrl: null,
      dialogVisible: false,
      dialogImageUrl: false,
      selectoricon:true,
      cascadeOptions:[],
      cascadeProps: {
        value: 'id',
        label: 'label',
        checkStrictly: this.column.checkStrictly||true,
        expandTrigger:'click',//hover
        emitPath:false,
		multiple: this.column.multiple||false,
		lazy:false,
    	isFocused:false,

		lazyLoad(node,resolve){
			resolve(node.children);
		}
	  },
		isReadonly:false,
		serverUrl:null,
    }
  },
  watch: {
    model: {
      async handler() {
		  if (this.drag) {
			  this.column.defaultValue = this.model[this.column.code];
		  }

		  ////判断是否需要重新加载位置
		  if(this.column.code.includes('storePlaceId')&&!this.isReadonly){
			  //查看同时编辑的有没有使用部门，如果有的话，那么需要重新按部门加载可用位置
			  let needCheckPosition = false;
			  for(let code in this.model){
				  if(code.includes("usingDepartmentId")){
					  needCheckPosition = true;
				  }
			  }
			  if(needCheckPosition===false){
				  return;
			  }

			  if(!this.model.usingDepartmentId&&this.model.storePlaceId){
				  this.$message.warning("请先选择资产的最终使用部门")
				  this.model.storePlaceId = null;
				  return null;
			  }


			  let needReloadPosition = false;
			  let lastUsingDepartmentId = this.column._lastUsingDepartmentId;

			  // console.log("needReloadPosition",lastUsingDepartmentId,this.model.usingDepartmentId);
			  if (!lastUsingDepartmentId) {
				  needReloadPosition = true;
			  } else {
				  if (lastUsingDepartmentId !== this.model.usingDepartmentId) {
					  needReloadPosition = true;
				  }
			  }

			  if (needReloadPosition===true) {
				  if(this.model.usingDepartmentId){
					  this.column.permissionData = [];
					  let rsp = await this.$API.asset.assetPosition.findPositionIdsRangeByOrgId.post({orgId: this.model.usingDepartmentId});
					  if (rsp.code === 2000) {
						  this.column._lastUsingDepartmentId = this.model.usingDepartmentId;
						  this.column.permissionData = rsp.data;
						  this.column.permissionData.push('');//如果没有可用位置，则添加一个空id，控制不显示任何位置
						  this.column.key = this.column.key+"1";//重新渲染组件
						  // console.log("reloadPositions",lastUsingDepartmentId,this.column.permissionData)
					  }
				  }
				  if(lastUsingDepartmentId){
					  this.model.storePlaceId = null;
				  }
			  }
		  }

	  },
      deep: true,
      immediate: false,
    },
    column:{
      handler() {
          this.cascadeProps.checkStrictly = this.column.checkStrictly;
		  if(this.drag){
			  this.isReadonly = this.column.isReadonly === '1';
			  this.column._editFlag = !this.isReadonly;
		  }
      },
      deep: true,
      immediate: true,
    }
  },
  async created() {
  },
  async mounted() {
	  this.serverUrl = await tool.minioServerUrl();
	  if(this.drag){
		  this.isReadonly = this.column.isReadonly==='1';
		  this.column._editFlag = !this.isReadonly;
	  }else{
		  this.isReadonly = this.column.isReadonly==='1'||(this.model._props&&this.model._props._editFlag===false);
		  this.column._editFlag = !this.isReadonly;
	  }

    if (!this.model[this.column.code]) {
      this.model[this.column.code] = this.column.defaultValue;
      //判断是不是在other中存放，并检查changeinfo中是否有变更后的值，如果有的话则赋值显示
      if (this.column.jsonColumnCode==='other') {
        let changeInfoColumnKey=this.column.code;
        if(this.column.isDynamic==='1'){
          changeInfoColumnKey = this.column.dynamicCode+"."+this.column.code;
        }
        if(this.topModel["changeInfo"]&&this.topModel["changeInfo"][changeInfoColumnKey]){
          this.model[this.column.code] = this.topModel["changeInfo"][changeInfoColumnKey]['after'];
        }
      }
      //如果还是没有值，判断是否显示默认原值，如果是的话，显示原值
      if(!this.model[this.column.code]&&this.column.showOldValue===true){
        if(this.topModel["assetInfo"]){
          if(this.column.isDynamic==='1'){
		    if(this.topModel["assetInfo"][this.column.dynamicCode]){
				this.model[this.column.code] = this.topModel["assetInfo"][this.column.dynamicCode][this.column.code];
		    }
          }else{
            this.model[this.column.code] = this.topModel["assetInfo"][this.column.code];
          }
        }
      }
    }
	  //判断字段是滞设置为空值时隐藏，如果是的否，并且为非编辑状态，则不显示
	  if(this.column.isEmptyHidden===true&&this.column._editFlag===false&&!this.model[this.column.code]){
		  this.column.columnHiden = true;
		  //console.log(this.column.columnHiden)
	  }

    if (this.column.widgetType === 'file') {
		// console.log(this.column.code,this.model[this.column.code]);
      if (this.model[this.column.code]) {
		// console.log(this.column.code,this.model[this.column.code]);
        let fileList = JSON.parse(this.model[this.column.code]);
		if(Array.isArray(fileList)){
			fileList.forEach(file=>{
				if(!file.url){
					file.url = this.serverUrl+file.realUrl;
				}else if(!file.url.startsWith('./')){
					file.url = this.serverUrl+file.realUrl;
				}
			})
		}
		this.tempFileList =fileList;
      }
    }
	  if(this.column.widgetType === 'tree-select'){//支持多选和单选，如果是多选的时候，数值的类型为数组，否则为字符串
		  if(this.column.multiple===false&&(!this.model[this.column.code]||Array.isArray(this.model[this.column.code]))){
			  this.model[this.column.code] = null;
		  }
		  if(this.column.multiple===true&&(!this.model[this.column.code]||!Array.isArray(this.model[this.column.code]))){
			  this.model[this.column.code] = [];
		  }
	  }

	  if (this.column.widgetType === 'cascade'||this.column.widgetType === 'tree-select'&&!this.isReadonly) {
		 let cascadeOptions = await this.$cache.tree.options(this.column.dataSourceCode, {parentLevelCode: "0000000"});

		  if(this.column.dataRange||(this.column.dataPermissionProcess!==undefined&&this.column.dataPermissionProcess!==false)){//数据权限处理
			  // console.log(this.column.code,this.column);
			  await this.dataPermissionProcess(cascadeOptions,this.column.permissionData,this.column.dataRange);
		  }
		  //字段为资产ID时，判断可用资产分类，单据资产分类权限处理
		  if(this.column.code==='assetCategoryId'){
			  if(this.model._props&&this.model._props.assetCategoryIds){
				  this.filterParentNode(this.model._props.assetCategoryIds,cascadeOptions);
				  this.displayNode(cascadeOptions,false);
			  }else{
				  this.displayNode(cascadeOptions,true);
			  }
		  }else{
			  this.displayNode(cascadeOptions,true);
		  }

		  //字段为位置时，根据可操作的位置过滤数据
		  if(this.column.code==='storePlaceId'){
			  if(this.model._props){
				  let managePositionIds = this.$TOOL.current.managePositionIds();
				  if(this.column.permissionData&&Array.isArray(this.column.permissionData)){
					  managePositionIds = this.column.permissionData;
				  }
				  if(!managePositionIds){
					  managePositionIds=[''];
				  }
				  this.filterParentNode(managePositionIds,cascadeOptions);
				  this.displayNode(cascadeOptions,true);
			  }else{
				  this.displayNode(cascadeOptions,true);
			  }
		  }else{
			  this.displayNode(cascadeOptions,true);
		  }

		  this.cascadeOptions = cascadeOptions.filter(option=>option.canRemove===false);

      if(this.column.widgetType === 'tree-select'&&this.column.disabledNode===true){
        this.disabledNode(cascadeOptions);
      }
	  }
    if(this.column.widgetType==='file' && this.column.listType==='text'){
        let height=45+(this.tempFileList.length*24);
        this.$emit('changeHeight',height);
      }
    this.isAlready = true;
  },
  methods: {
	  async dataPermissionProcess(data,permissionData,rangeType) {
		  if (Array.isArray(data)) {
			  //获取管理范围
			  let manageDeptIds = tool.current.manageDeptIds();
			  let manageCategoryIds = tool.current.manageAssetCategoryIds();

			  if(permissionData&&Array.isArray(permissionData)){
				  manageDeptIds = permissionData;
				  manageCategoryIds = permissionData;
			  }else{
				  //根据管理管理获取数据
				  if(rangeType){
					  if(rangeType==='manageRange'||rangeType==='excludeManageRange'){//登录人的管理范围
						  manageDeptIds = tool.current.manageDeptIds();
					  }else if(rangeType==='readRange'||rangeType==='excludeReadRange'){//登录人的查看范围
						  manageDeptIds = tool.current.readDeptIds();
					  }else if(rangeType==='orgRange'||rangeType==='excludeOrgRange'){//登录人的组织范围
						  manageDeptIds = tool.current.innerRangeDeptIds();
					  }else if(rangeType==='assetOrgRange'||rangeType==='excludeAssetOrgRange'){//资产的组织范围
						  // console.log("this.topModel",this.column.code,this.topModel);
						  manageDeptIds =[];
						  if(this.topModel&&this.topModel.originalAssetInfo&&this.topModel.originalAssetInfo.usingDepartmentId){
							  let rsp = await this.$API.system.dept.findOrgIdsRangeByOrgId.post({orgId:this.topModel.originalAssetInfo.usingDepartmentId});
							  if (rsp.code === 2000) {
								  manageDeptIds = rsp.data;
							  }
						  }
					  }else if(rangeType==='all'){
						  return;
					  }
					  permissionData = manageDeptIds;
				  }
			  }

			  if(rangeType&&rangeType.includes('exclude')){
				  for (const item of data) {
					  if (item.entityName === 'SysOrganization' && manageDeptIds && !item.disabled) {
						if(item.disabled!==true){
						  item.disabled = manageDeptIds.includes(item.id);
						}
					  }
					  if (item.entityName === 'FamsAssetCategory' && manageCategoryIds && !item.disabled) {
						if(item.disabled!==true){
						  item.disabled = manageCategoryIds.includes(item.id);
						}
					  }
					  if (item.children) {
						  await this.dataPermissionProcess(item.children,permissionData,rangeType);
					  }

				  }
			  }else{
				  for (const item of data) {
					  if (item.entityName === 'SysOrganization' && manageDeptIds && !item.disabled) {
						  if(item.disabled!==true){
							item.disabled = !manageDeptIds.includes(item.id);
						  }
								  }
								  if (item.entityName === 'FamsAssetCategory' && manageCategoryIds && !item.disabled) {
						  if(item.disabled!==true){
							item.disabled = !manageCategoryIds.includes(item.id);
						  }
					  }
					  if (item.children) {
						  await this.dataPermissionProcess(item.children,permissionData,rangeType);
					  }
				  }
			  }
		  }
	  },
    filterParentNode(ids,options){
      if(Array.isArray(ids)&&ids.length>0){
        options.forEach(option=>{
          option.disabled= !ids.includes(option.id);
          if(option.children){
            this.filterParentNode(ids,option.children);
          }
        });
      }
    },
    disabledNode(options){//禁用节点，保留叶子节点可用
		  options.forEach(option=>{
			  option.value=option.id;
			  if(option.children){
				  option.disabled = true;
				  this.disabledNode(option.children);
			  }
		  });
	  },
	  displayNode(options,keepBranch){//keepBranch是否保留分支
			 let tempOptions = [];
		  options.forEach(option=>{
			  option.value=option.id;
			  if(option.children){
				  this.displayNode(option.children,keepBranch);
				  let realChildren = option.children.filter(child=>child.disabled===false||child.children!==null);
				  if(realChildren.length>0){
					  option.children = realChildren;
				  }else{
					  option.children = null;
				  }
				  if(option.children === null&&!keepBranch){
					  option.disabled = true;
				  }
			  }
			  option.canRemove = (option.children===null && option.disabled===true);
			  if(option.canRemove===false){
				  tempOptions.push(option);
			  }
		  });
		  options = tempOptions;
	  },

    async beforeUpload(file) {

		// this.column.fileType = "image/png";
		if (this.column.fileType && (!file.type || !file.type.includes(this.column.fileType))) {
			this.$message.warning({message: this.$t("common.upload_type_limit", {type: this.column.fileType})});
			return false;
		}
		if (this.column.maxLength) {
			let fileSize = this.column.maxLength * 1024 * 1024;
			if (file.size >= fileSize) {
				this.$message.warning({message: this.$t("common.upload_filesize_limit", {filesize: this.column.maxLength})});
				return false;
			}
		}

		//当字段为资产标签时，使用js读取资产标签中的二维码，判断是否和资产编码一致
		if (this.column.code === 'assetLabelImage'&&this.column.fileType==='image') {
      this.$message.warning({message: this.$t("common.asset_label_image_decoding")});
			let qrCode = await this.decodeQRCode(file);
			if(!qrCode||!qrCode.qrCodeData){
				this.$message.error({message: this.$t("common.asset_label_image_decode_error")});
				return false;
			}
			let assetCode = this.topModel.code||this.topModel.assetInfo.code;
			if(!qrCode.qrCodeData.includes(assetCode)){
				this.$message.error({message: this.$t("common.asset_label_image_error")});
				return false;
			}
      this.$message.success({message: this.$t("common.asset_label_image_success")});
		}
		return true;
	},
    handleExceed(file, files) {
      this.$message.warning({message: this.$t("common.upload_count_limit", {limit: files.length})});
    },
    handleSuccess(response, uploadFile, uploadFiles) {
      // console.log("handleSuccess",response,uploadFile,uploadFiles);
    },
    handleRemove(uploadFile, uploadFiles) {
       // console.log("handleRemove",uploadFile,uploadFiles);
      if (this.tempFileList.length === 0) {
        this.model[this.column.code] = null;
      } else {
        this.model[this.column.code] = JSON.stringify(this.tempFileList);
      }

    },

    async handlePictureCardPreview(uploadFile) {
		this.dialogImageUrl = this.serverUrl + uploadFile.realUrl;
		if (uploadFile.type.includes("image")) {
			this.dialogVisible = true;
		} else {
			this.$message.warning({message: this.$t("common.file_can_not_preview")});
			window.open(this.dialogImageUrl);
		}
	},
    async submitUpload(content) {
      let fd = new FormData();
      fd.append("file", content.file);
      let rsp = await this.$API.common.upload.post(fd, {});
      if (rsp.code === 2000) {
        let currentFile = {
          name: content.file.name,
          type: content.file.type ? content.file.type : content.file.name.substring(content.file.name.lastIndexOf(".") + 1),
          size: content.file.size,
          status:"success",
          realUrl: rsp.data,
          url: rsp.data,
        };
        if (!content.file.type.includes("image")) {
          currentFile.url = "./img/404.png";
        }
        /*
         <template v-if="column.widgetType==='file'">
		  <template v-if="column.listType==='text'">
        */

          if(this.column.widgetType==='file' && this.column.listType==='text'){
            let height=45+(this.tempFileList.length*24);
            this.$emit('changeHeight',height);
          }


        this.tempFileList[this.tempFileList.length - 1] = currentFile;
        this.model[this.column.code] = JSON.stringify(this.tempFileList);
		//重新替换tempFileList最后一个上传的文件，做展示使用，不要删除
	  	if (content.file.type.includes("image")) {
		  currentFile.url = this.serverUrl+currentFile.url;
	      this.tempFileList[this.tempFileList.length - 1] = currentFile;
	  	}
      }
    },
    download(file){
      this.$TOOL.file.open(file.realUrl,true,file.name);
    },
    removefile(file) {
      let newtemplist=[];
      for(let i=0;i<this.tempFileList.length;i++){
        if(this.tempFileList[i].realUrl!=file.realUrl){
          newtemplist.push(this.tempFileList[i]);
        }
      }
      this.tempFileList=newtemplist;

      if (this.tempFileList.length === 0) {
        this.model[this.column.code] = '';
      } else {
        this.model[this.column.code] = JSON.stringify(this.tempFileList);
      }

    },

	  handleCheck(data, checkData) {
		  if(this.column.multiple===false){
			  return false;
		  }
		  let checkIds = checkData.checkedKeys;
		  // console.log("handleCheck", data, checkData);
		  //判断当前节点是否被选中
		  let checked = true;
		  if (checkData.checkedKeys.filter(key => key === data["id"]).length === 0) {
			  checked = false;
		  }
		  if(checked&&data.children){
			  this.$confirm('是否选中所有下级节点', '提示', {type: 'info'}).then(() => {
				  //获取当前节点下所有子节点的id
				  let childrenIds = [];
				  if (data.children) {
					  childrenIds = this.childrenKeys(data.children);
				  }
				  // //合并原始勾选的id和当前节点下所有的子节点的id,并使用set去重
				  let setKeys = new Set([...checkIds, ...childrenIds]);
				  checkIds = Array.from(setKeys);
				  // //重新设置树的勾选状态
				  this.model[this.column.code] = checkIds;
				  this.setCheckedKeys(checkIds);
				  return true;
			  }).catch(() => {
				  return false;
			  });
		  }

	  },
	  childrenKeys(children) {
		  let keys = [];
		  if (Array.isArray(children)) {
			  children.forEach(item => {
				  keys.push(item["id"]);
				  if (item.children) {
					  let childrenKeys = this.childrenKeys(item.children);
					  childrenKeys.forEach(key => {
						  keys.push(key);
					  });
				  }
			  })
		  }
		  return keys;
	  },
	  setCheckedKeys(checkKeys) {
		  if (this.$refs && this.$refs.treeSelect) {
			  this.$refs.treeSelect.setCheckedKeys(checkKeys);
		  }
	  },
    focusHandler() {
      this.isFocused = true; // 获取焦点时显示
    },
    blurHandler() {
      this.isFocused = false; // 失去焦点时隐藏
    },

	  decodeQRCode(file) {
      let reader = new FileReader();
		  let imageData = new Image();
		  return new Promise((resolve,reject)=>{
			  reader.onload = (e) => {
				  imageData.onload = () => {
            let qrCodeData = null;
            for (let i = 0;i< 5;i++){
              console.log("放大读取",1+i*0.5);
              qrCodeData = this.readQrCode(imageData,1+i*0.5);
              if(qrCodeData){
                break;
              }
            }
            if (qrCodeData) {
              resolve({qrCodeData});
            } else {
              this.splitImageAndDecode(imageData, resolve);
            }
				  };
				  imageData.src = e.target.result;
			  };
			  reader.readAsDataURL(file);
		  });
	  },
    splitImageAndDecode(image,resolve) {
      let qrCodeData = null;

      qrCodeData = this.decodeByCrop(image);
      if (qrCodeData) {
        resolve({qrCodeData});
        return ;
      }
      qrCodeData = this.decodeBySplit(image,4);
      if (qrCodeData) {
        resolve({qrCodeData});
        return ;
      }

      resolve({});
    },
    readQrCode(imageData,canvasSide){
      let canvas = document.createElement("canvas");
      let context = canvas.getContext('2d');
      canvas.width = canvasSide*imageData.width;
      canvas.height = canvasSide*imageData.height;
      context.drawImage(imageData, 0, 0, canvas.width, canvas.height);
      let imageDataArray = context.getImageData(0, 0, canvas.width, canvas.height).data;
      let qrCodeData = this.decodeCanvasData(imageDataArray,canvas.width,canvas.height);
      if (qrCodeData) {
        return qrCodeData;
      }
      return null;
    },
    decodeByCrop(image){
      let tryCrop = true;
      let tryTimes = 1;
      let cropLength = 50;
      while(tryCrop){
        let tempLength = tryTimes*cropLength;
        if(tempLength>=image.width||tempLength>=image.height){
          tryCrop = false;
        }
        if(tryCrop){
          let qrCodeData = this.decodeCropImage(image,tempLength);
          if(qrCodeData){
            tryCrop = false;
            return qrCodeData;
          }else{
            tryTimes++;
          }
        }
      }
      return null;
    },
    decodeCropImage(image, cropLength) {
      let canvas = document.createElement("canvas")
      let context = canvas.getContext('2d');
      canvas.width = image.width;
      canvas.height = image.height;
      context.drawImage(image, cropLength, cropLength, image.width, image.height, 0, 0, canvas.width, canvas.height);
      this.openImage(canvas,"裁剪读取"+cropLength);
      let imageDataArray = context.getImageData(0, 0, canvas.width, canvas.height).data;
      let qrCodeData = this.decodeCanvasData(imageDataArray,canvas.width,canvas.height);
      if (qrCodeData) {
        return qrCodeData;
      }else{
        return null;
      }
    },
    decodeBySplit(image,split){
      if(!split||split===0){
        split = 3;
      }
      for (let i=1;i<=split;i++){
        for(let j=1;j<=split;j++){
          let qrCodeData = this.decodeSplitImageData(image, i,j);
          if (qrCodeData) {
            return qrCodeData;
          }
        }
      }
      return null;
    },
    decodeSplitImageData(image,columns,rows) {
      let tileWidth = image.width / columns;
      let tileHeight = image.height / rows;

      for (let i = 0;i<columns;i++){
        for(let j = 0;j<rows;j++){
          let x = i * tileWidth;
          let y = j * tileHeight;
          let canvas = document.createElement('canvas');
          let ctx = canvas.getContext('2d');
          canvas.width = tileWidth*3;
          canvas.height = tileHeight*3;
          ctx.drawImage(image, x, y, tileWidth, tileHeight, 0, 0, canvas.width, canvas.height);
          this.openImage(canvas,"切割读取_"+columns+'x'+rows+'_'+(i+1)+'_'+(j+1));
          let imageDataArray  = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
          let qrCodeData = this.decodeCanvasData(imageDataArray,canvas.width,canvas.height);
          if (qrCodeData) {
            return qrCodeData;
          }
        }
      }
      return null;
    },

    decodeCanvasData(canvasData,canvasWidth,canvasHeight){
      let code = jsQR(canvasData, canvasWidth, canvasHeight);
      if (code) {
        console.log(code);
        let qrCodeData = code.data;
        console.log('QR Code Data:', qrCodeData);
        return qrCodeData;
      }
      return null;
    },

    openImage(canvas,preFix){
      console.log(preFix);
      // let dataURL = canvas.toDataURL('image/png');
      // // 创建下载链接
      // const downloadLink = document.createElement('a');
      // downloadLink.href = dataURL;
      // downloadLink.download = preFix+'.png';
      // // 模拟点击下载链接
      // downloadLink.click();
    },

    splitImage(image, columns, rows) {
      let canvas = document.createElement('canvas');
      let ctx = canvas.getContext('2d');
      let count = columns * rows;
      let tileWidth = image.width / columns;
      let tileHeight = image.height / rows;

      canvas.width = tileWidth;
      canvas.height = tileHeight;

      let tiles = [];

      for (let i = 0; i < count; i++) {
        let x = (i % columns) * tileWidth;
        let y = Math.floor(i / rows) * tileHeight;

        ctx.drawImage(image, x, y, tileWidth, tileHeight, 0, 0, tileWidth, tileHeight);
        let imageDataArray  = ctx.getImageData(0, 0, canvas.width, canvas.height).data;
        // console.log(imageDataArray);
        let dataURL = canvas.toDataURL('image/png');
        let img = new Image();
        img.src = dataURL;
        tiles.push(img);
      }

      return tiles;
    }
  }
}
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  width: 110px;
  height: 110px;
}

.avatar-uploader .el-upload-list__item {
    width: 110px;
  height: 110px;
  object-fit: contain;
}

.avatar-uploader .el-upload-list__item.is-success:focus:not(:hover) {
  display: none !important;
}

.avatar-uploader-hidden .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
	width: 110px;
  height: 110px;
	display: none;
}

.avatar-uploader-hidden .el-upload-list__item {
	width: 110px;
  height: 110px;
	object-fit: contain;
}

.avatar-uploader-hidden .el-upload-list__item.is-success:focus:not(:hover) {
	display: none !important;
}

.filetemplist2{
  height: 120px;
  overflow-y: auto;
}
.filetemplist3{
  height: 170px;
  overflow-y: auto;
}
.filetemplist4{
  height: 230px;
  overflow-y: auto;
}
.fileTemp{
padding-right: 20px;
height: 24px;
}
.fileTemp .fileTempleft{
  float: left;
  padding-right: 20px;
  height: 24px !important;
}
.fileTemp .fileTempleft p{
 cursor: pointer;
}
.fileTemp .fileTempright{
  float: right;
  height: 24px;
  margin-right: 30%;
}
.fileTemp:hover .fileTempleft{
  background-color: #ebf5ff;

}
.fileTemp:hover .fileTempleft p{
  text-decoration: underline;
}

.el-cascader-node {
  max-width: 200px;
}

.el-upload-list__item-actions{
  padding-left: 10px;
  padding-right: 10px;
}
.itemcontent{
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap; /* 防止换行 */
}
</style>
